import os
from flask import Flask, session
from flask_session import Session
from redis import Redis
from flask import request


class config:
    SESSION_TYPE = 'redis'  # session存储到redis中
    host = '39.96.7.141'  # redis服务器地址
    port = 6379  # redis端口
    SESSION_REDIS = Redis(host=host, port=port, db=0)
    SESSION_USE_SIGNER = True  # 是否加盐
    SECRET_KEY = os.urandom(24)  # 加的盐， 使用os.urandom(24)生成随机的盐
    SESSION_PERMANENT = True  # session是否长期有效，如果为False，关闭浏览器session失效
    PERMANENT_SESSION_LIFETIME = 60  # session的过期时间
    DEBUG = True


app = Flask(__name__)
app.config.from_object(config)
Session(app)


# 设置session
@app.route('/add/')
def add():
    session['username'] = 'fengling'
    return '设置session'


# 查看session
@app.route('/select/')
def select():
    a = request.cookies.get('session')
    b = a.split('.')[0]
    print(b)
    print(session)
    if b in session:
        return print('b')
    username = session.get('username', 'not set')
    return username



# 删除session
@app.route('/pop/')
def pop():
    session.pop('username', 'not set')
    return session.get('key', 'not set')

# 清空session
@app.route('/clear/')
def clear():
    session.clear()
    return session.get('key', 'not set')


if __name__ == "__main__":
    app.run(debug=True)
